import React, { useState } from 'react';
import { Space, Typography, MessagePlugin, Row, Col } from 'tdesign-react';
import { TodoForm } from '../components/todos/TodoForm';
import { TodoList } from '../components/todos/TodoList';
import { useTodos, useCreateTodo, useCompleteTodo, useRemoveTodo } from '../hooks/use-todos';
import type { CreateTodoInput } from '../types/todo.types';

const backgroundStyle: React.CSSProperties = {
  minHeight: '100vh',
  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%)',
  position: 'relative',
  overflow: 'hidden',
  padding: '16px 0',
};

const contentContainerStyle: React.CSSProperties = {
  position: 'relative',
  zIndex: 2,
  backgroundColor: 'rgba(255, 255, 255, 0.95)',
  borderRadius: '20px',
  padding: '32px',
  backdropFilter: 'blur(10px)',
  boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)',
  maxWidth: '1200px',
  margin: '0 auto',
};

const titleStyle: React.CSSProperties = {
  textAlign: 'center',
  fontWeight: 700,
  marginBottom: '32px',
  textShadow: '0 2px 4px rgba(0,0,0,0.1)',
};

export const TodosView: React.FC = () => {
  const [updatingId, setUpdatingId] = useState<number | null>(null);

  const { data: todosData, isLoading, error: fetchError } = useTodos();
  const createTodoMutation = useCreateTodo();
  const completeTodoMutation = useCompleteTodo();
  const removeTodoMutation = useRemoveTodo();

  const handleCreateTodo = async (input: CreateTodoInput) => {
    try {
      await createTodoMutation.mutateAsync(input);
      MessagePlugin.success('待办事项创建成功');
    } catch {
      MessagePlugin.error('创建待办事项失败');
    }
  };

  const handleCompleteTodo = async (id: number) => {
    setUpdatingId(id);
    try {
      await completeTodoMutation.mutateAsync(id);
      MessagePlugin.success('待办事项已完成');
    } catch {
      MessagePlugin.error('完成待办事项失败');
    } finally {
      setUpdatingId(null);
    }
  };

  const handleRemoveTodo = async (id: number) => {
    setUpdatingId(id);
    try {
      await removeTodoMutation.mutateAsync(id);
      MessagePlugin.success('待办事项已删除');
    } catch {
      MessagePlugin.error('删除待办事项失败');
    } finally {
      setUpdatingId(null);
    }
  };

  return (
    <div style={backgroundStyle}>
      <div style={contentContainerStyle}>
        <Typography.Title level="h1" style={titleStyle}>
          📝 我的待办事项
        </Typography.Title>
        
        <Row gutter={[24, 24]}>
          <Col xs={24} lg={12}>
            <TodoForm
              onSubmit={handleCreateTodo}
              isLoading={createTodoMutation.isPending}
            />
          </Col>
          
          <Col xs={24} lg={12}>
            <TodoList
              todos={todosData?.data || []}
              onComplete={handleCompleteTodo}
              onRemove={handleRemoveTodo}
              isLoading={isLoading}
              error={fetchError}
              updatingId={updatingId}
            />
          </Col>
        </Row>
      </div>
    </div>
  );
};